from apps.chat.message.baseViews import *
from apps.chat.message.service import sendMessage
from apps.chat.conversation.models import Conversation
from apps.chat.message.models import Message
from apps.chat.message.dao import MessageDao

class MessageViewSet(BaseMessageViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = MessageDao().findAll().select_related('befrom')
        if not params.get('conversation'):
            _list = Message.objects.none()
        return _list.order_by('-createTime')

    '''发送消息'''
    @action(methods=['post'], detail=False)
    def sendMessage(self, request):
        params = getRequestParams(request)
        _userId= params.get('userId')
        if not _userId:
            return Response(response_message('发送对象不能为空'))
        if isEmptyStr(params.get('content')):
            return Response(response_message('发送内容不能为空'))
        if isEmptyStr(params.get('contentType')):
            return Response(response_message('contentType参数必填'))
        if request.user.checkStatus == 'INITIAL':
            return Response(response_message('该账号未认证，不允许该操作'))
        
        res = sendMessage(request.user, params)
        return Response(response_success(res))

    '''读取消息'''
    @action(methods=['post'], detail=False, url_path='readMessage')
    def readMessageAPI(self, request):
        params = getRequestParams(request)
        conversation = Conversation.objects.get(id=params.get('conversationId'))
        if conversation.conversationType == 'system':
            messageList = Message.objects.filter(conversation=params.get('conversationId'), isRead=False)
        else:
            messageList = Message.objects.filter(conversation=params.get('conversationId'), isRead=False).exclude(befrom=request.user)
        messageList.update(isRead=True)
        return Response(response_success('操作成功'))